#include <iostream>
#include <algorithm>
#include <string>
#include <cstdio>
#include <vector>
#include <stack>
#include <queue>
#include <set>
using namespace std;
struct ListNode
{
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
    vector<ListNode *> nodeList;
    ListNode *swapPairs(ListNode *head)
    {
        ListNode *ptr = head;
        if (ptr == nullptr || ptr->next == nullptr)
            return ptr;
        while (ptr != nullptr)
        {
            nodeList.push_back(ptr);
            ptr = ptr->next;
        }
        ListNode *nHead = head->next, *ptr1 = nullptr, *ptr2 = nullptr;
        for (int i = 0; 2 * i < nodeList.size(); ++i)
        {
            ptr1 = nullptr;
            ptr2 = nullptr;
            if (2 * i + 1 < nodeList.size())
                ptr2 = nodeList[2 * i + 1];
            if (2 * i < nodeList.size())
                ptr1 = nodeList[2 * i];
            if (ptr2 != nullptr)
                ptr2->next = ptr1;
            if (2 * i + 3 < nodeList.size())
                ptr1->next = nodeList[2 * i + 3];
            else if (2 * i + 2 < nodeList.size())
                ptr1->next = nodeList[2 * i + 2];
            else
                ptr1->next = nullptr;
        }
        return nHead;
    }
};